import { Request, Response, NextFunction } from 'express';
import { TokenService } from '../services/token-service';
import { UserService } from '../services/user-service';

// 扩展Request接口以包含用户信息
declare global {
  namespace Express {
    interface Request {
      user?: {
        id: string;
        name: string;
        email: string;
        avatar?: string;
        position?: string;
      };
    }
  }
}

export const authMiddleware = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        success: false,
        message: '未提供有效的认证token'
      });
    }
    
    const token = authHeader.replace('Bearer ', '');
    const userId = await TokenService.validateToken(token);
    
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: 'token无效或已过期'
      });
    }
    
    // 获取用户信息
    const user = await UserService.getUserById(userId);
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 将用户信息添加到请求对象中
    req.user = {
      id: user.id,
      name: user.name,
      email: user.email,
      avatar: user.avatar,
      position: user.position
    };
    
    next();
  } catch (error) {
    console.error('Auth middleware error:', error);
    res.status(500).json({
      success: false,
      message: '认证失败'
    });
  }
};

export const validateRequest = (schema: any) => {
  return (req: Request, res: Response, next: NextFunction): void => {
    try {
      // In a real application, you would validate the request against the schema
      // For now, we'll just pass through
      next();
    } catch (error) {
      res.status(400).json({
        success: false,
        message: '请求数据无效'
      });
    }
  };
};